package com.achilles.learnasyncqueryhandler;

import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity implements ContactsDataAsyncQueryHandler
        .ContactsDataInterface {

    public static final int REQUEST_CODE_READ_CONTACTS = 0;
    private ListView mListView;
    private ListViewAdapter mListViewAdapter;
    private ContactsDataAsyncQueryHandler mContactsDataAsyncQueryHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContactsDataAsyncQueryHandler = new ContactsDataAsyncQueryHandler(getContentResolver(),
                this);
        mListView = (ListView) findViewById(R.id.listview);
        mListViewAdapter = new ListViewAdapter(this);
        mListView.setAdapter(mListViewAdapter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (checkPermissions()) {
            startQueryData();
        }
    }

    private void startQueryData() {
        Uri uri = Uri.parse("content://com.android.contacts/data/phones");
        String[] projection = {"display_name", "data1"};
        mContactsDataAsyncQueryHandler.startQuery(0, null, uri, projection, null, null, null);
    }

    @Override
    public void updateDatas(List<ContactsDataModel> contactsDataModels) {
        mListViewAdapter.updateDatas(contactsDataModels);
    }

    private boolean checkPermissions() {
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission
                    .READ_CONTACTS}, REQUEST_CODE_READ_CONTACTS);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_READ_CONTACTS: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startQueryData();
                } else {
                    Toast.makeText(MainActivity.this, "can not read contacts datas", Toast
                            .LENGTH_SHORT).show();
                }
                break;
            }
        }
    }
}
